package com.jumper.property.comparer.diff.value;

import com.alibaba.fastjson.JSON;
import com.jumper.property.comparer.core.bean.CombinationPropertySetting;
import com.jumper.property.comparer.core.bean.PropertySetting;
import com.jumper.property.comparer.diff.Diff;
import com.jumper.property.comparer.diff.DiffVal;
import com.jumper.property.comparer.formatter.CombinationDiffFormatter;
import com.jumper.property.comparer.util.ListUtil;
import com.jumper.property.comparer.util.ValueUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 组合属性差异获取
 */
public class CombinationDiff implements Diff {

    private final CombinationPropertySetting setting;
    private final List<String> beforeValues;
    private final List<String> afterValues;

    public CombinationDiff(CombinationPropertySetting setting, Object beforeData, Object afterData) {
        this.setting = setting;
        List<PropertySetting> settings = setting.getCombinationProperties();
        this.beforeValues = settings.stream().map(e -> ValueUtil.getStrValue(beforeData, e.getField())).collect(Collectors.toList());
        this.afterValues = settings.stream().map(e -> ValueUtil.getStrValue(afterData, e.getField())).collect(Collectors.toList());
    }

    @Override
    public List<DiffVal> getDiffValues() {
        if (noChange()) {
            return new ArrayList<>();
        }
        return ListUtil.toList(new DiffVal(
                beforeValues, afterValues, getDiffValue()
        ));
    }

    private boolean noChange() {
        return Objects.equals(JSON.toJSONString(beforeValues), JSON.toJSONString(afterValues));
    }

    private String getDiffValue() {
        return new CombinationDiffFormatter(setting.getCombinationName(), beforeValues, afterValues).format();
    }
}
